define(['config', 'text!app/module/system/addOrder.html', 'laypage',
    'mydialog', 'autocomplete', 'jqGrid', 'common', 'laydate'
], function (config, viewHTML, laypage,
    mydialog, autocomplete, jqGrid, common, laydate) {
	
	var token = (cache.go("token") === 'undefined') ? 'none' : cache.go("token");
	
	var num = "";
	
	var businessId;

    var grid_arr = new Array();
    
    var product_arr = new Array();

    var businessIds = Public.getRequestParam ("businessId");
    
    var select_arr = new Array();
    
    var last_arr = new Array();
    
    var arr = new Array();
    
    var ids = [];
    
    var item = 0;
    
    var areaId;
    
    var model = avalon.define({
    	$id : "addOrder",
    	selected:'',
         // 查询条件
         query: {
        	 businessIds: "",
         },
         arsUnit: [
                   {
                       key: "件",
                       val: '011'
                   }
               ],
          areaproductinfo :{
     			  id:"",
     			  productId:"",
     			  areaId:"",
     			  numb:"",
     			  floorPrice:"",
     			  retailPrice:"",
     			  createTime:"",
     			  createUser:"admin",
     			  productName:"",
     			  describes:"",
     			  remarks:"",
     			  model:"",
     			  businessId:""
     	  },
     	  
     	  areaIdVo:{
     		  areaId:""
     	  },
     	  
         arsTypeSearch:function(){
           },
           
          arsType:select_arr,
          
	      isEmpty: function (value, alerttxt) {
	          if (value == null || value == "") {
	              Public.tips({
	                      type: 2,
	                      content: alerttxt
	                  });
	               return false;
           }else {
	              return true;
	       }
	     },
	     temp:{
	    	 
	     },
	     businessInfo:{
	    	 id:businessId,
             name: "",
             level: "",
             areaId: "",
             describe:"",
             createTime:"",
             createUser: ""
	    	 
	     },
         orderInfo:{
        	 id: "",
             name: "",
             level: "",
             areaId: "",
             describe:"",
             createTime:"",
             createUser: ""
         },
         orderDetailInfo :{
             id:"",
             name:"",
             describe:"",
             createTime:"",
             createUser:""
             },
         statusArr: [],
         selected: [],
         roles: [],
         
         init: function () {
        	 model.initPage();
             model.addEvent();
             model.initorder();
         },
         /** 接收orders页面传的orderNo */
         initPage:function(){
        	 businessId = businessIds;
	        	 function t(val, opt, row) {
	            	
	        		 
	        		 var html_con = '<div class="operating" data-id="' + row.id + '"><span class="fa fa-edit mrb" title="修改"><a href="index.html#!/108"/></span><span class="fa fa-trash-o mrb" title="删除"></span>' + (row.is_deleted == 1 ? '<span class="fa fa-reply mrb" title="恢复"></span>' : '') + '</div>';
	            	 
	        		 return html_con;
	             }
	        	 function a(val, opt, row) {
	               	 var html_con ;
	               		 html_con = '<div class="productionInstructionStatus" data-id="' + row.id + '"><a class = "view" id="detail"><span>添加/查看设备</span></a></div>';
	               	 return html_con;
	                }
	        	 
	        	 function ft(val, opt, row){
	        		 
	        	 }
        	 	if(businessIds){
        	 		console.log('[name]',businessIds);
        	 		 $.ajax({
                         type: "POST",
                         url: "/api/businessList/findBybusinessIds",
                         data: {
                        	 "page":1,
                        	 "rows":1,
                             "businessId": businessIds
                         },
                         beforeSend: function (xhr) {
                             xhr.setRequestHeader("X-AuthToken", token);
                         },
                         success: function (data) {
                        	 model.orderInfo = data.data;
                         },
                         error: function (responseData, textStatus, errorThrown) {
                             alert("Failed: " + JSON.stringify(responseData));
                         }
                     }); 
        	 		$.ajax({
                        type: "POST",
                        url: "api/businessList/getList",
                        data: {
                        	"businessId":businessIds
                        },
                        beforeSend: function (xhr) {
                            xhr.setRequestHeader("X-AuthToken", token);
                        },
                        success: function (data) {
                       	 console.log('[data]',data);
                       	 grid_arr = data.data;
                       	 console.log('[grid_arr]',grid_arr);
                       	 model.reLoadGrid();
                       	 
                        },
                        error: function (responseData, textStatus, errorThrown) {
                            alert("Failed: " + responseData);
                        }
                    });
        	 	}else{
        	 		$.ajax({
            			 type:"POST",
            			 url: "/api/order/serialNo",
            			 success:function(data){
            				 console.log("/.lfjasdl;fkjasd;lf",data)
            				 model.orderInfo.id=data;
            				 businessId = data;
            				 console.log('businessId1111111111111111111111111111111111111111111111111:',model.orderInfo.id);
            				 console.log('businessId1111111111111111111111111111111111111111111111111:',businessId);
            			 },
            			 beforeSend: function (xhr) {
            				 xhr.setRequestHeader("X-AuthToken", token);
            			 },
            			 error: function (responseData, textStatus, errorThrown) {
            				 alert("Failed: " + JSON.stringify(responseData));
            			 }
            		  	});
       	 		 model.orderInfo.id = businessId;
              	 console.log("lakjsfhkjashfkjlasdf",businessId);
              	 console.log("lakjsfhkjashfkjlasdf",businessIds);
        	 	}
        	 	var quantity = 0;
        	 	var unitPrice = 0;
            	$("#grid").jqGrid({
    		     datatype: "local",
    		     data:grid_arr,
                 colModel: [{
                           name: "operating",
                           label: "操作",
                           width: '5%',
                           formatter: t
                       },
                       {
                    	   name:"id",
                    	   label: "id",
                    	   width: '8%',
                    	   hidden: true,
//                    	   formatter: function(value,options,rowData){
//                    		   areaId = value;
//                    		   console.log("12awdasdkj;hasfidhasiudhasd",areaId);
//                    	   }
                       },
                       {
                           name: "name",
                           label: "功能区名称",
                           width: '16%',
                       },
                       {
                           name: "createUser",
                           label: "创建人",
                           width: '16%'
                       }
                       /*,
                       {
                           name: "doserch",
                           label: "添加/修改设备",
                           width: '16%',
                           formatter: a
                       }*/
                       /*
						 * , { name: "unitPrice", label: "单价", width: '13%', //
						 * formatter:function(value, options, rowData){ //
						 * unitPrice = value; // return unitPrice; // } }, {
						 * name: "amount", label: "总价", width: '13%', //
						 * formatter:function(value, options, rowData){ //
						 * return unitPrice*quantity; // } }
						 */
                   ],
                   page: 1,
                   rowNum: 10,
                   rowList: [10, 20, 30],
                   height: '250px',
                   autowidth: true,
                   pager: '#page',
                   sortname: 'id',
                   viewrecords: true,
                   forceFit: false,
                   rownumbers: true,
                   multiselect: true,
                   multiboxonly: true,
                   sortorder: "desc",
                   /* 单击行数据 显示从表 */
                   onSelectRow: function(rowId) {
//                	   areaId = "";
                       model.id = $("#grid").jqGrid("getRowData", rowId).id;
                       var id=$('#grid').jqGrid('getGridParam','selrow');
                       var rowData = $("#grid").jqGrid('getRowData',id);
                       console.log("rowData",rowData.id);
                       areaId = rowData.id;
                       console.log("rowData",areaId);
                       num = 1;
                       console.log("点击获取："+rowData);
                       model.reLoadGrid_d();
                       

                   },
                   caption : "功能区域列表"
		    		 });
            	$("#grid_d").jqGrid({
				     datatype: "local",
				     data:arr,
				     colNames : [ '操作','id' ,'设备名称','规格','单价','数量','建议零售价'],
           		     colModel : [ 
           		                 {name : 'act',index : 'act',width : 75,formatter: t},
           		                 {name : 'id',index : 'id',width : 120,align : "right",hidden:true} ,
           		                 {name : 'productName',index : 'productName',width : 180},
           		                 {name : 'model',index : 'model',width : 120,align : "right"}, 
           		                 {name : 'floorPrice',index : 'floorPrice',width : 120,align : "right"}, 
           		                 {name : 'numb',index : 'numb',width : 120,align : "right",editable:true}, 
           		                 {name : 'retailPrice',index : 'retailPrice',width : 120,align : "right"} 
           		               ],
		               page: 1,
		               rowNum: 10,
		               rowList: [10, 20, 30],
		               height: '250px',
		               autowidth: true,
		               pager: '#page',
		               sortname: 'id',
		               viewrecords: true,
		               forceFit: false,
		               rownumbers: true,
		               multiselect: true,
		               multiboxonly: true,
		               sortorder: "desc",
		               /* 单击行数据 显示从表 */
		               /*onSelectRow: function(rowId) {
		              	 
		                   model.id = $("#grid").jqGrid("getRowData", rowId).id;
		                   console.log("点击获取："+model.id);
		                   model.reLoadGrid_d();
		            	   var r=$("#grid_d").jqGrid('getRowData',id);//r为当前数据行
	            	       jQuery('#grid_').editRow(id, true); 
		
		               },*/

		                 caption : "设备清单"
				 });
	         },
         reLoadGrid: function () {
        	 $.ajax({
                 type: "POST",
                 url: "api/businessList/getList",
                 data: {
                 	"businessId":businessId
                 },
                 beforeSend: function (xhr) {
                     xhr.setRequestHeader("X-AuthToken", token);
                 },
                 success: function (data) {
                	 console.log('[data]',data);
                	 grid_arr = data.data;
                	 console.log('[grid_arr1111111111111111111111]',grid_arr);
//                	 model.reLoadGrid();
                	 $("#grid").jqGrid("setGridParam", {
                    	 datatype: "local",
            		     data:grid_arr,
                         page:1,
                     }).trigger("reloadGrid");
                 },
                 error: function (responseData, textStatus, errorThrown) {
                     alert("Failed: " + responseData);
                 }
             });
//             $("#grid").jqGrid("setGridParam", {
//            	 datatype: "local",
//    		     data:grid_arr,
//                 page:1,
//             }).trigger("reloadGrid");
         },
         reLoadGrid_d: function () {
        	 $.ajax({
                 type: "POST",
                 url: "api/businessList/getProductList",
                 data: {
                	"areaId":areaId,
                 	"businessId":businessId
                 },
                 beforeSend: function (xhr) {
                     xhr.setRequestHeader("X-AuthToken", token);
                 },
                 success: function (data) {
                	 console.log('[data]',data);
                	 arr = [];
                	 arr = data.data;
                	 if(arr == undefined){
                		 arr = [];
                	 }
                	 console.log('[grid_arr]',arr);
                	 $("#grid_d").jqGrid("setGridParam", {
                    	 datatype: "local",
            		     data:arr,
                         page:1,
                     }).trigger("reloadGrid");
                	 
                 },
                 error: function (responseData, textStatus, errorThrown) {
                     alert("Failed: " + responseData);
                 }
             });
             
         },
         
         
         
         // 添加或更新
         addProduct: function () {
           /** 自动匹配商品 */
           $("#productName").autocomplete({
           serviceUrl: "/api/businessList/getProduct",
           paramName: "name",
           minLength: 0,  
           // 其他ajax配置
           ajaxSettings: {
               beforeSend: function (xhr) {
                   xhr.setRequestHeader("X-AuthToken", token);
               },
           },
           showNoSuggestionNotice: true,
           noSuggestionNotice: '无匹配项',
           onSearchStart: function (query) {
           },
           transformResult: function (response) {
	       var obj = $.parseJSON(response);
	       console.log('obj.data',obj);
	       return {
	           suggestions: $.map(obj, function (data) {
	               return {
	            	   value: "设备名称："+data.name,
	                   data: data
	               };
	           })
	       };
         },
           onSelect: function (suggestion) {
        	   model.initareaproductinfo();
        	   console.log('[suggestion.data]',suggestion.data);
        	   model.areaproductinfo.id = suggestion.data.id;
        	   model.areaproductinfo.areaId =areaId;
               model.areaproductinfo.productName = suggestion.data.name;
               model.areaproductinfo.describes = suggestion.data.describes;
               model.areaproductinfo.model = suggestion.data.model;
               model.areaproductinfo.floorPrice = suggestion.data.floorPrice;
               model.areaproductinfo.retailPrice = suggestion.data.retailprice;
               model.areaproductinfo.createTime = suggestion.data.createTime;
               model.areaproductinfo.createUser = suggestion.data.createUser;
               model.areaproductinfo.businessId = businessId;
               
// model.orderDetailInfo.floorPrice = suggestion.data.floorPrice;
// model.orderDetailInfo.retailPrice = suggestion.data.retailPrice;
           },
           onSearchComplete: function (query, suggestions) {
               $("div[data-index=0]").addClass("autocomplete-selected");
           }
       });
             dialog({
                 title: '选择设备信息',
                 content: $('#editProduct1'),
                 okValue: "确定",
                 ok:function addRow(){
                	 console.log("123123123123",num);
//                	 if(model.isEmpty(num,"请先选择功能区域！")){
// 					
//                	 }else{
                			var selectedId = $("#grid_d").jqGrid("getGridParam", "selrow"); 
     						console.log('selectedId',selectedId);
     						var rowData = model.areaproductinfo.$model;   
     						console.log('[rowData]',rowData);
     						var rowid = rowData.id;
     						if (selectedId) {         
     							$("#grid_d").jqGrid("addRowData", rowid, rowData, "after", selectedId);
     						} else {  
     							$("#grid_d").jqGrid("addRowData", rowid, rowData, "last");     
     						}  
     						arr.push(rowData);
     						console.log('11111',arr);
     						$.ajax({
     	                         type: "POST",
     	                          url: "/api/businessList/saveAreaProduct" ,
     	                          contentType: "application/json;",
     	                          data: JSON.stringify(arr),
     	                          beforeSend: function (xhr) {
     	                              xhr.setRequestHeader("X-AuthToken", token);
     	                          },
     	                          success: function (data) {
     	                        	  model.reLoadGrid_d();
//     	                        	  areaId = "";
     	                          },
     		                           error: function (responseData, textStatus, errorThrown) {
     	                              alert("系统异常");
     	                          }
     	                      });
//                	 }
                 },
                 cancelValue: "取消",
                 cancel: function () {}
             }).showModal();
         },
         
         editProduct:function (obj,t) {
        	 model.orderDetailInfo=$("#grid").jqGrid('getRowData', t);
        	 console.log('[model.orderDetailInfo]',model.orderDetailInfo);
        	 /** 自动匹配商品 */
           $("#productName").autocomplete({
    	   serviceUrl: "/api/businessList/getProduct",
           paramName: "name",
           minLength: 0,  
           // 其他ajax配置
           ajaxSettings: {
               beforeSend: function (xhr) {
                   xhr.setRequestHeader("X-AuthToken", token);
               },
           },
           showNoSuggestionNotice: true,
           noSuggestionNotice: '无匹配项',
           onSearchStart: function (query) {
               // if (model.depart.parentID != "") {
               // model.depart.parentID = "";
               // }
           },
           transformResult: function (response) {
             var obj = $.parseJSON(response);
             console.log('obj.data',obj);
             return {
                 suggestions: $.map(obj, function (data) {
                     return {
                         value: "设备名称："+data.name,
                         data: data
                     };
                 })
             };
         },
           onSelect: function (suggestion) {
               model.initareaproductinfo();
        	   console.log('[suggestion.data]',suggestion.data);
        	   model.areaproductinfo.id = suggestion.data.id;
               model.areaproductinfo.productName = suggestion.data.name;
               model.areaproductinfo.describes = suggestion.data.describes;
               model.areaproductinfo.model = suggestion.data.model;
               model.areaproductinfo.floorPrice = suggestion.data.floorPrice;
               model.areaproductinfo.retailPrice = suggestion.data.retailprice;
               model.areaproductinfo.createTime = suggestion.data.createTime;
               model.areaproductinfo.createUser = suggestion.data.createUser;
               model.areaproductinfo.businessId = businessId;
           },
           onSearchComplete: function (query, suggestions) {
               $("div[data-index=0]").addClass("autocomplete-selected");
           }
       });
		     dialog({
		         title: '编辑商品信息',
		         content: $('#editProduct1'),
		         okValue: "确定",
		         ok:function(){
		    	     for (var i = 0; i < arr.length; i++) {
						if(arr[i].id == t){
							arr[i] = model.areaproductinfo.$model;
//							grid_arr[i].orderNo = model.orderInfo.orderNo;
//							grid_arr[i].id = new Date().getTime();
							console.log('[grid_arr]',arr);
//							model.reLoadGrid_d();
						}
					}
		    	     $.ajax({
                         type: "POST",
                          url: "/api/businessList/saveAreaProduct" ,
                          contentType: "application/json;",
                          data: JSON.stringify(arr),
                          beforeSend: function (xhr) {
                              xhr.setRequestHeader("X-AuthToken", token);
                          },
                          success: function (data) {
                        	  model.reLoadGrid_d();
//                        	  areaId = "";
                          },
	                           error: function (responseData, textStatus, errorThrown) {
                              alert("系统异常");
                          }
                      });
		         },
		         cancelValue: "取消",
		         cancel: function () {}
		     }).showModal();
         },
         
         
         
         // 添加或更新
         add: function () {
           /** 自动匹配商品 */
           $("#areaName").autocomplete({
           serviceUrl: "/api/businessList/getArea",
           paramName: "name",
           minLength: 0,  
           // 其他ajax配置
           ajaxSettings: {
               beforeSend: function (xhr) {
                   xhr.setRequestHeader("X-AuthToken", token);
               },
           },
           showNoSuggestionNotice: true,
           noSuggestionNotice: '无匹配项',
           onSearchStart: function (query) {
           },
           transformResult: function (response) {
	       var obj = $.parseJSON(response);
	       console.log('obj.data',obj);
	       return {
	           suggestions: $.map(obj, function (data) {
	               return {
	            	   value: "功能区名称："+data.name,
	                   data: data
	               };
	           })
	       };
         },
           onSelect: function (suggestion) {
        	   model.initorderDetail();
        	   console.log('[suggestion.data]',suggestion.data);
        	   model.orderDetailInfo.id = suggestion.data.id;
               model.orderDetailInfo.name = suggestion.data.name;
               model.orderDetailInfo.describes = suggestion.data.describes;
               model.orderDetailInfo.createTime = suggestion.data.createTime;
               model.orderDetailInfo.createUser = suggestion.data.createUser;
               model.orderDetailInfo.areaId = areaId;
               model.orderDetailInfo.businessId = businessId;
// model.orderDetailInfo.floorPrice = suggestion.data.floorPrice;
// model.orderDetailInfo.retailPrice = suggestion.data.retailPrice;
           },
           onSearchComplete: function (query, suggestions) {
               $("div[data-index=0]").addClass("autocomplete-selected");
           }
       });
             dialog({
                 title: '选择设备信息',
                 content: $('#editUser'),
                 okValue: "确定",
                 ok:function addRow(){
// 						var selectedId = $("#grid").jqGrid("getGridParam", "selrow"); 
// 						console.log('selectedId',selectedId);
// 						var rowData = model.orderDetailInfo.$model;   
// 						console.log('[rowData]',rowData);
// 						var rowid = rowData.id;
// 						if (selectedId) {         
// 							$("#grid").jqGrid("addRowData", rowid, rowData, "after", selectedId);
// 						} else {  
// 							$("#grid").jqGrid("addRowData", rowid, rowData, "last");     
// 						}  
// 						grid_arr.push(rowData);
// 						model.orderDetailInfo.areaId = areaId;
// 						console.log('11111',grid_arr);
 						$.ajax({
 	                         type: "POST",
 	                          url: "/api/businessList/saveAreaList" ,
 	                          contentType: "application/json;",
 	                          data: JSON.stringify(model.orderDetailInfo),
 	                          beforeSend: function (xhr) {
 	                              xhr.setRequestHeader("X-AuthToken", token);
 	                          },
 	                          success: function (data) {
 	                        	  model.reLoadGrid();
 	                          },
 		                           error: function (responseData, textStatus, errorThrown) {
 	                              alert("系统异常");
 	                          }
 	                      });
 						
                 },
                 cancelValue: "取消",
                 cancel: function () {}
             }).showModal();
         },
         
         edit:function (obj,t) {
        	 model.orderDetailInfo=$("#grid").jqGrid('getRowData', t);
        	 console.log('[model.orderDetailInfo]',model.orderDetailInfo);
        	 /** 自动匹配商品 */
           $("#areaName").autocomplete({
    	   serviceUrl: "/api/businessList/getArea",
           paramName: "name",
           minLength: 0,  
           // 其他ajax配置
           ajaxSettings: {
               beforeSend: function (xhr) {
                   xhr.setRequestHeader("X-AuthToken", token);
               },
           },
           showNoSuggestionNotice: true,
           noSuggestionNotice: '无匹配项',
           onSearchStart: function (query) {
               // if (model.depart.parentID != "") {
               // model.depart.parentID = "";
               // }
           },
           transformResult: function (response) {
             var obj = $.parseJSON(response);
             console.log('obj.data',obj);
             return {
                 suggestions: $.map(obj, function (data) {
                     return {
                         value: "区域名称："+data.name,
                         data: data
                     };
                 })
             };
         },
           onSelect: function (suggestion) {
        	   model.initorderDetail();
        	   console.log('[suggestion.data]',suggestion.data);
        	   if(suggestion.data.unit === 011){
            	   model.orderDetailInfo.unit = "件";
               }
        	   model.initorderDetail();
        	   console.log('[suggestion.data]',suggestion.data);
        	   model.orderDetailInfo.id = suggestion.data.id;
               model.orderDetailInfo.name = suggestion.data.name;
               model.orderDetailInfo.areaId = areaId;
               model.orderDetailInfo.businessId = businessId;
               model.orderDetailInfo.describes = suggestion.data.describes;
               model.orderDetailInfo.createTime = suggestion.data.createTime;
               model.orderDetailInfo.createUser = suggestion.data.createUser;
           },
           onSearchComplete: function (query, suggestions) {
               $("div[data-index=0]").addClass("autocomplete-selected");
           }
       });
		     dialog({
		         title: '编辑商品信息',
		         content: $('#editUser'),
		         okValue: "确定",
		         ok:function(){
		    	     for (var i = 0; i < grid_arr.length; i++) {
						if(grid_arr[i].id == t){
							grid_arr[i] = model.orderDetailInfo.$model;
//							grid_arr[i].orderNo = model.orderInfo.orderNo;
//							grid_arr[i].id = new Date().getTime();
							console.log('[grid_arr]',grid_arr);
							model.reLoadGrid();
						}
					}
		    	     
						$.ajax({
	                         type: "POST",
	                          url: "/api/businessList/saveAreaList" ,
	                          contentType: "application/json;",
	                          data: JSON.stringify(model.orderDetailInfo),
	                          beforeSend: function (xhr) {
	                              xhr.setRequestHeader("X-AuthToken", token);
	                          },
	                          success: function (data) {
	                        	  model.reLoadGrid();
	                          },
		                           error: function (responseData, textStatus, errorThrown) {
	                              alert("系统异常");
	                          }
	                      });
		         },
		         cancelValue: "取消",
		         cancel: function () {}
		     }).showModal();
         },
         /** 删除商品 */
         del:function(id){
        	 dialog({
                 title: "确认操作",
                 content: "确定删除？ 此操作不可恢复！",
                 okValue: "确定",
                 ok: function () {
                	 for (var i = 0; i < grid_arr.length; i++) {
    						if(grid_arr[i].id == id){
    							model.orderInfo.totalQuantity = parseInt(model.orderInfo.totalQuantity) - parseInt(grid_arr[i].quantity);
    							grid_arr.splice(i,1);
    							$('#grid').jqGrid('delRowData', id);
    							console.log('[grid_arr]',grid_arr);
    						}
					   } 
                	 model.reLoadGrid();
                 },
                 cancelValue: "取消",
                 cancel: function () {}
             }).showModal();
         },
         
         //下达生产指令
         Issued: function (product_arr) {
//        	 console.log("rowData",rowData);
//        	 if(rowData.productionInstructionStatus == '已下达'){
//            	 $.ajax({
//            		 type:"POST",
//            		 url:"/api/produce/list",
//            		 data:{
//            			 "orderNo":rowData.orderNo,
//            		 },
//            		 success: function (data) {
//            			 console.log('[data1111111111111111111111111111]',data);
//        				 model.productionInfo=data.data;
//        				 console.log('[model.productionInfo]',model.productionInfo);
//        				 model.productionInfo.startingDate = Public.custDatefmter(model.productionInfo.startingDate);
//        				 
//    					 $("#editUser input").attr("readOnly","true");
//    					 $("#editUser textarea").attr("readOnly","true");
//    					 $("#startingDate").removeAttr("onclick");
//            		 },
//            		 beforeSend: function (xhr) {
//                         xhr.setRequestHeader("X-AuthToken", token);
//                     },
//                     error: function (responseData, textStatus, errorThrown) {
//                         alert("Failed: " + responseData);
//                     }
//            	 });
//        	 }else if(rowData.productionInstructionStatus ===''||rowData.productionInstructionStatus === 0){
//        		 model.initproduction();
//	        	 $.ajax({
//	    			 type:"POST",
//	                 url: "/api/produce/getProductionNo",
//	                 success:function(data){
//	                	 console.log('[data]',data);
//	                	 model.initproduction();
//	                	 productionNo = data;
//	                	 model.productionInfo.productionNo=data;
//	                 },
//
//	                 beforeSend: function (xhr) {
//	                     xhr.setRequestHeader("X-AuthToken", token);
//	                 },
//	                 error: function (responseData, textStatus, errorThrown) {
//	                     alert("Failed: " + responseData);
//	                 }
//	    		 });
//        	 }
             dialog({
                 title: '下达生产指令',
	                 content: $('#editProduct'),
                 okValue: "确定",
                 ok: function () {
                	 for (var i = 0; i < product_arr.length; i++) {
                 		model.initareaproductinfo();
                 		model.areaproductinfo.id = "";
                 		model.areaproductinfo.productId = product_arr[i].id;
                 		model.areaproductinfo.areaId = areaId;
                 		model.areaproductinfo.numb = product_arr[i].numb;
                 		model.areaproductinfo.floorPrice = product_arr[i].floorPrice;
                 		model.areaproductinfo.retailPrice = product_arr[i].retailprice;
                 		model.areaproductinfo.createTime = "";
                 		model.areaproductinfo.createUser = "admin";
                 		model.areaproductinfo.productName = product_arr[i].name;
                 		model.areaproductinfo.describes = "";
                 		model.areaproductinfo.remarks = "";
                 		model.areaproductinfo.model = product_arr[i].model;
                 		model.areaproductinfo.businessId = businessId;
                 		arr.push(model.areaproductinfo.$model);
                 		console.log('grid_arr',arr); 	  	
						}
                    		  console.log("product_arr",arr);
                         	 if(item == 1){
                        		 dialog({
                                     title: "错误！",
                                     content: "请勿重复提交！",
                                     okValue: "确定",
                    	        	 ok: function (){
                    	        	 }
                            	 }).showModal();
                        		 return;  
                        	 }
                      	    $.ajax({
                                type: "POST",
                                 url: "/api/businessList/saveAreaProduct" ,
                                 contentType: "application/json;",
                                 data: JSON.stringify(arr),
                                 beforeSend: function (xhr) {
                                     xhr.setRequestHeader("X-AuthToken", token);
                                 },
                                 success: function (data) {
                                	 console.log("data",arr);
                                	 model.reLoadGrid_d();
//                                	 if(data.success == false && data.status == 1){
//                                		 dialog({
//                                             title: "错误！",
//                                             content: "物料库存不足，不能生产 ！",
//                                             okValue: "确定",
//                            	        	 ok: function (){
//                            	        	 }
//                                    	 }).showModal();
//                                	 }else if(data.status == 0){
//                                		 item = 1;
//                                		 model.reLoadGrid();
//                                		 dialog({
//                                             title: "下达生产任务成功！",
//                                             content: "下达生产任务成功！",
//                                             okValue: "确定",
//                            	        	 ok: function (){
//                            	        	 }
//                                    	 }).showModal();
//                                	 }
                                 },
      	                           error: function (responseData, textStatus, errorThrown) {
                                     alert("系统异常");
                                 }
                             });
                    	  
                 },
                 cancelValue: "取消",
                 cancel: function () {}
             }).showModal();
         },
         
         addEvent: function () {
             var t = this;
             // 返回
             $(".fr").on("click", "#close", function (e){
            	 console.log('1111111111111111111111');
                 top.topManager.closePage();
                 
             });
             
        	 /** 下达订单*/
             $(".grid-wrap").on("click", ".view", function (e) {
            	 var t = $(this).parent().data("id");
            	 var id = $("#grid").jqGrid("getGridParam", "selarrrow");
            	 var rowData = $("#grid").jqGrid('getRowData',id);
            	 console.log("111111111111111111111111111111111111111111111111",rowData);
	            	 /**dialog中显示子表*/
                 $("#grid_a").jqGrid({
                	 loadBeforeSend: function (jqXHR) {
                         jqXHR.setRequestHeader("X-AuthToken", token);
                     },
                     datatype: "json",
                     
                     url: "api/goods/list",
                     mtype: 'POST',
                     cache:false,
                     postData: {
//                    	 "orderNo" : orderNo
                    	          },
    	             loadComplete:function (data) {
                    	 
//                    	console.log('data======',data);
//                    	console.log('model.productionDetailInfo11111111111111111111112222222222222222222',model.productionDetailInfo.$model);
                    	for (var i = 0; i < data.length; i++) {
//                    		model.initproductionDetailInfo();
//                    		console.log('[model.productionDetailInfo]'+i,model.productionDetailInfo);
//                    		console.log('data[i].sku',data[i].sku);
//                    		console.log('data[i].uuid',data[i].uuid);
//                    		model.productionDetailInfo.orderDetailUuid = data[i].uuid;
//                    		model.productionDetailInfo.sku = data[i].sku;
//                    		model.productionDetailInfo.name = data[i].name;
//                    		model.productionDetailInfo.orderNo = data[i].orderNo;
//                    		model.productionDetailInfo.model = data[i].model;
//                    		model.productionDetailInfo.amount = data[i].quantity;
//                    		model.productionDetailInfo.already = data[i].already;
//                    		model.productionDetailInfo.alreadyOut = data[i].alreadyOut;
//                    		model.productionDetailInfo.goodsUuid = data[i].goodsUuid;
//                    		console.log('model.productionDetailInfo',model.productionDetailInfo.$model);
//                    		grid_arr.push(model.productionDetailInfo.$model);
//                    		console.log('grid_arr',grid_arr); 	  	
						}
                    	
                    	
                    	 
                     },
                     loadError: function (xhr, status, error) {
//                         alert(JSON.parse(xhr.responseText).msg);
                     },
                     colNames : [ 'id' ,'设备名称','规格','单价','数量','建议零售价'],
           		     colModel : [ 
           		                 {name : 'id',index : 'id',width : 120,align : "right",hidden:true} ,
           		                 {name : 'name',index : 'name',width : 180},
           		                 {name : 'model',index : 'model',width : 120,align : "right"}, 
           		                 {name : 'floorPrice',index : 'floorPrice',width : 120,align : "right"}, 
           		                 {name : 'numb',index : 'numb',width : 120,align : "right"}, 
           		                 {name : 'retailprice',index : 'retailprice',width : 120,align : "right"} 
           		               ],
                     cmTemplate: {
                     sortable: false,
                     title: false
                     },
//                     page: 1,
//                     rowNum: 10,
//                     rowList: [10, 20, 30],
//                     pager: '#page',
                     sortname: 'id',
                     viewrecords: true,
                     forceFit: false,
                     rownumbers: true,
                     multiselect: true,
                     multiboxonly: true,
                     sortorder: "desc",
                     autoScroll: false,
                     height: 150,
                     altRows: true,
                     gridview: true,
                     autowidth: true,
                     
                     /* 单击行数据   显示从表*/
                     onSelectRow: function(rowId) {
                    	 
//	                         model.id = $("#grid").jqGrid("getRowData", rowId).id;
	                         
	                         var id=$('#grid_a').jqGrid('getGridParam','selrow');
	                         
//	                         ids=$('#grid_a').jqGrid('getGridParam','selarrrow');
	                         
	                         console.log("点击获取：",id);
	                         
	                         var rowData = $("#grid_a").jqGrid('getRowData',id);
	                         
	                         console.log("rowdata",rowData);
	                         if(product_arr.length == 0){
	                        	 product_arr.push(rowData);
	                         }
	                         for(var i = 0;i < product_arr.length;i++){
	                        	 console.log(product_arr[i].id);
	                        	 if(id == product_arr[i].id){
	                        		 return;
	                        	 }
	                         }
	                         product_arr.push(rowData);
	                         console.log("123123123123123123123123123:",product_arr);
                     },
                     jsonReader: {
                         root: "data.list",
                         records: "data.totalRow",
                         total: "data.totalPage",
                     },
                 });
	            	 model.Issued(product_arr);
                
             });

             // 添加商品
             $(".grid-wrap").on("click", "#addGoods", function (e) {
            	 console.log("grid_arr.length:"+grid_arr.length);
            		 model.initorderDetail();
            		 model.add();
             });
             $(".grid-wrap").on("click", "#addProduct", function (e) {
            	 if(model.isEmpty(num,"请先选择功能区域！")){
            		 model.initareaproductinfo();
            		 model.addProduct();
            	 }
             });
             $(".grid-wrap").on("click", ".fa-edit", function (e) {
            	 var selectedId = $("#grid").jqGrid("getGridParam","selrow"); 
                 console.log('grid_arr',grid_arr);
        	     console.log('1111111',selectedId);
                 model.edit($("#grid").getRowData(selectedId),selectedId);
           });
             // 提交表单
             $(".fr").on("click","#save",function(e){
            	 model.orderInfo.id = businessId;
            	 $.ajax({
            		 contentType: "application/json;",
                     type: "POST",
                     url: "/api/businessList/save",
                     data:JSON.stringify(model.orderInfo),
                     beforeSend: function (xhr) {
                         xhr.setRequestHeader("X-AuthToken", token);
                     },
                     success: function () {
                    	 model.temp = model.orderInfo;
	                    	 dialog({
	                           title: "保存成功",
	                           content: "保存成功！",
	                           okValue: "确定",
	          	        	 ok: function (){
	          	        	 }
	                  	 }).showModal();
                    	 item = 1;
                     },
                     error: function (responseData, textStatus, errorThrown) {
                    	 dialog({
	                           title: "保存失败",
	                           content: "保存失败！",
	                           okValue: "确定",
	          	        	 ok: function (){
	          	        	 }
	                  	 }).showModal();
                     }
                 });
             });
          // 导出
             $(".fr").on("click","#export",function(e){
            	 model.orderInfo.id = businessId;
            	 $.ajax({
            		 contentType: "application/x-www-form-urlencoded",
                     type: "POST",
                     url: "/api/export/exportList",
//                     data:JSON.stringify(model.orderInfo),
                     data:{
                    	 "businessId" : "F1579489737179"
                    	 },
                     beforeSend: function (xhr) {
                         xhr.setRequestHeader("X-AuthToken", token);
                     },
                     responseType:'blob',
                     success: function (data) {
                    	 var blob = this.response;
                    	 var a = document.createElement('a');
                         a.href = "/api/export/exportList.do?businessId=F1579489737179";
                         //设置文件名称
                         a.download = '营业厅设备清单.xls';
                         a.click();
                     },
                     error: function (responseData, textStatus, errorThrown) {
                    	 dialog({
	                           title: "保存失败",
	                           content: "保存失败！",
	                           okValue: "确定",
	          	        	 ok: function (){
	          	        	 }
	                  	 }).showModal();
                     }
                 });
             });
             $(".grid-wrap").on("click", ".fa-trash-o", function (t) {
            	 var selectedId = $("#grid").jqGrid("getGridParam","selrow"); 
              	   model.del(selectedId);
             });
         },
         initorder: function () {
          	model.orderInfo={
	         		id: "",
	                name: "",
	                level: "",
	                areaId: areaId,
	                describes:"",
	                createTime:"",
	                createUser: ""
          	}
          },
         initorderDetail: function () {
             model.orderDetailInfo = {
            		 id:"",
                     name:"",
                     describes:"",
                     createTime:"",
                     createUser:"",
                     areaId:"",
                 }
             },
          initareaproductinfo:function(){
        	  model.areaproductinfo = {
        			  id:"",
        			  productId:"",
        			  areaId:areaId,
        			  numb:"",
        			  floorPrice:"",
        			  retailPrice:"",
        			  createTime:"",
        			  createUser:"admin",
        			  productName:"",
        			  describes:"",
        			  remarks:"",
        			  model:"",
        			  businessId:""
        	  }
          }
    });
    
    // 定义视图模块
    var viewmod = {
        viewtSrc: viewHTML,
        viewInit: function () {
            model.init();
        }, // 模块view加载完成后的回调方法，在刷新（F5）时可能调用两次
        viewDestroy: function () {} // 切换菜单时销毁原来的view
    };
    return viewmod;
	
	
});